﻿using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.BO.DHQG;
using DHQGHN.DAL.Common;
using DHQGHN.DAL.Models.DHQG;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM2.Models.DHQG;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DHQGHN.PM2.Controllers
{
    public class NguoiDungAdminController : BaseController
    {
        private NguoiDungAdminBO _sqlBO;
        private NhomDonViBO _sqlNhomDVBO;
        private DonViBO _sqlDonViBO;
        public ActionResult Index(NguoiDungModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string curentID = "")
        {
            SetActiveMenu("/NguoiDungAdmin/Index");
            if (a == null) a = new NguoiDungModel();
            a.DELETED = 2;            

            _sqlNhomDVBO = new NhomDonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            //List<NhomDonVi> items = _sqlNhomDVBO.GetAll();
            //chi get nhom co ban
            List<NhomDonVi> items = _sqlNhomDVBO.GetNhomDVByType_New(1);
            List<SelectListItem> lstNhomDonVi = new List<SelectListItem>();
            lstNhomDonVi.Add(new SelectListItem
            {
                Text = "Chọn nhóm đơn vị",
                Value = "0"
            });
            for (int i = 0; i < items.Count; i++)
            {
                lstNhomDonVi.Add(new SelectListItem
                {
                    Text = items[i].TenNhomDonVi,
                    Value = items[i].NhomDonViId.ToString()
                });
            }

            _sqlDonViBO = new DonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            List<DonVi> temp = _sqlDonViBO.GetAllDonViByNhom(a.NHOM_DON_VI_ID);
            List<SelectListItem> lstDonVi = new List<SelectListItem>();
            lstDonVi.Add(new SelectListItem
            {
                Text = "Chọn đơn vị",
                Value = "0"
            });
            for (int i = 0; i < temp.Count; i++)
            {
                lstDonVi.Add(new SelectListItem
                {
                    Text = temp[i].TenDonVi,
                    Value = temp[i].DonViId.ToString()
                });
            }

            ViewBag.lstNhomDonVi = lstNhomDonVi;
            ViewBag.lstDonVi = lstDonVi;

            var model = Search(a, pageIndex, curentID, false);
            return View(model);
        }

        [HttpPost]
        public ActionResult CreatePopupUpdate(string id)
        {
            //_sqlNhomDVBO = new NhomDonViBO();
            _sqlNhomDVBO = new NhomDonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            //List<NhomDonVi> items = _sqlNhomDVBO.GetAll();
            //lay nhom don vi co ban de loc don vi
            List<NhomDonVi> items = _sqlNhomDVBO.GetNhomDVByType_New(1);
            
            List<SelectListItem> lstNhomDonVi = new List<SelectListItem>();
            lstNhomDonVi.Add(new SelectListItem
            {
                Text = "Chọn nhóm đơn vị",
                Value = "0"
            });
            for (int i = 0; i < items.Count; i++)
            {
                lstNhomDonVi.Add(new SelectListItem
                {
                    Text = items[i].TenNhomDonVi,
                    Value = items[i].NhomDonViId.ToString()
                });
            }

            NguoiDungModel model = null;
            if (!String.IsNullOrEmpty(id) || !String.IsNullOrWhiteSpace(id))
            {
                //_sqlBO = GetSqlBO();
                _sqlBO = GetSqlBOFromPM0(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                int nguoiDungId = 0;
                if (int.TryParse(id, out nguoiDungId))
                {
                    model = new NguoiDungModel(_sqlBO.GetAdminById(nguoiDungId));
                    Session["UserBackup"] = model;                    
                }
            }
            else
            {
                model = new NguoiDungModel();
            }

            //_sqlDonViBO = new DonViBO();
            _sqlDonViBO = new DonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            //List<DonVi> temp = _sqlDonViBO.GetAllDonViByNhom(0);
            int intPara = 0;
            if (model == null)
            {
                intPara = 0;
            }
            else
            {
                intPara = model.NHOM_DON_VI_ID;
            }

            List<DonVi> temp = _sqlDonViBO.GetAllDonViByNhom(intPara);
            List<SelectListItem> lstDonVi = new List<SelectListItem>();
            lstDonVi.Add(new SelectListItem
            {
                Text = "Chọn đơn vị",
                Value = ""
            });
            for (int i = 0; i < temp.Count; i++)
            {
                lstDonVi.Add(new SelectListItem
                {
                    Text = temp[i].TenDonVi,
                    Value = temp[i].DonViId.ToString()
                });
            }

            ViewBag.lstNhomDonVi = lstNhomDonVi;
            ViewBag.lstDonVi = lstDonVi;

            
            if (model == null)
            {
                model = new NguoiDungModel();
            }
            if (Request.IsAjaxRequest())
            {
                return PartialView(model);
            }
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult ActionSave(NguoiDungModel model)
        {
            if (Request.IsAjaxRequest())
            {
                //_sqlBO = GetSqlBO();
                _sqlBO = GetSqlBOFromPM0(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                model.IS_ADMIN = 1;
                bool result = _sqlBO.Save(model.ToDALModel());
                if (result)
                {
                    if (model.NGUOI_DUNG_ID > 0)
                    {
                        NguoiDungModel oldUser = (Session["UserBackup"] != null ?
                            (NguoiDungModel)Session["UserBackup"] : (new NguoiDungModel()));
                        USER_GROUP_CREATE data = GetUserData(model, oldUser.TAI_KHOAN);
                        bool updateResult = UpdateUser(data);
                        if (updateResult)
                        {
                            return Json(JsonResponse.Json200("Cập nhật thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Xảy ra lỗi trong quá trình cập nhật sang hệ quản trị!"));
                        }
                    }
                    else
                    {
                        string message = "Thêm mới thành công!";
                        try
                        {
                            string maDv = string.Empty;
                            //if (Session["NguoiDungInfo"] != null)
                            //{
                            //    var nguoiDung = (NguoiDungModel)Session["NguoiDungInfo"];
                            //    maDv = nguoiDung.listDonVi.Count > 0 ? nguoiDung.listDonVi[0].MaDonVi : string.Empty;
                            //    //maDv = "KHTC";
                            //}

                            //phunx1, 20160418: truong hop them nguoi dung co quyen admin tai cac don vi
                            maDv = model.DON_VI_ID.ToString();

                            USER_GROUP_CREATE data = GetData(model);
                            var resultMessage = RegisterUser(data);
                            if (resultMessage.ErrorCode != 200)
                            {
                                message = resultMessage.ErrorMessage;
                            }
                        }
                        catch
                        {
                            throw;
                        }
                        return Json(JsonResponse.Json200(message));
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult ActionDelete(int[] id, string[] userName)
        {
            if (Request.IsAjaxRequest())
            {
                //_sqlBO = GetSqlBO();
                _sqlBO = GetSqlBOFromPM0(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                bool result = _sqlBO.Delete(id);
                if (result)
                {
                    bool deleteResult = deleteUser(userName, DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE);
                    if (deleteResult)
                    {
                        Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý trên hệ quản trị!"));
                    }
                    return Json(JsonResponse.Json200("Xóa thành công"));
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        public bool deleteUser(string[] userName, string appCode)
        {
            try
            {
                UserBO userBO = new UserBO();
                bool ret = userBO.deleteUser(userName, appCode);
                return ret;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost]
        public ActionResult ActionSearch(NguoiDungModel model = null, int pageIndex = 0, string sort = "CertificationId", string sortDir = "ASC", string currentId = "")
        {
            if (model == null)
            {
                model = new NguoiDungModel();
            }
            var dataPaging = Search(model, pageIndex, currentId, false);
            return PartialView("~/Views/NguoiDungAdmin/_NguoiDungAdminList.cshtml", dataPaging);
        }

        private DataPage<NguoiDungModel> Search(NguoiDungModel myModel, int pageIndex, string currentId, bool compareEqual)
        {
            //phunx1, nguoi dung la admin cac don vi
            myModel.IS_ADMIN = 1;

            _sqlBO = GetSqlBOFromPM0(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);

            var DALModel = _sqlBO.GetListAdminPaging(myModel.ToDALModel(), pageIndex, PageSize);
            var models = new DataPage<NguoiDungModel>();
            var lstItem = DALModel.Data;
            foreach (DHQGHN.DAL.Models.DHQG.NguoiDung nguoiDung in lstItem)
            {
                models.Data.Add(new NguoiDungModel(nguoiDung));
            }

            NguoiDungModel model = null;
            if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
            {
                model = models.Data.Find(user => user.NGUOI_DUNG_ID.Equals(currentId));
                models.CustomData = model;
            }
            else
            {
                models.CustomData = myModel;
            }
            if (models.Data.Count > 0)
            {
                //Tao component phan trang
                var pagNative = new Pagination
                {
                    ActionName = "ActionSearch",
                    ModelName = "NguoiDung",
                    CurrentPage = pageIndex,
                    InputSearchId = "",
                    TagetReLoadId = "certification-list",

                };
                pagNative.TotalRows = models.Data[0].RECORD_COUNT;
                pagNative.CurrentRow = models.Data.Count;
                ViewBag.Pagination = pagNative;
            }
            return models;
        }

        [AjaxValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Reactive(int nguoiDungId, string taiKhoan)
        {
            if (Request.IsAjaxRequest())
            {
                //_sqlBO = new NguoiDungBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                _sqlBO = GetSqlBOFromPM0(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                UserBO userBO = new UserBO();
                bool result = _sqlBO.Reactive(nguoiDungId);
                if (result)
                {
                    bool reactiveResult = userBO.Reactive(taiKhoan, DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE);
                    if (reactiveResult)
                    {
                        return Json(JsonResponse.Json200("Khôi phục người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        [HttpPost]
        public JsonResult GetDonViByNhom(string strNhomDonViID)
        {
            try
            {
                int intNhomDonViID = 0;
                //_sqlDonViBO = new DonViBO();
                _sqlDonViBO = new DonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                if (!string.IsNullOrEmpty(strNhomDonViID))
                {
                    intNhomDonViID = int.Parse(strNhomDonViID);
                }

                List<DonVi> temp = _sqlDonViBO.GetAllDonViByNhom(intNhomDonViID);
                List<SelectListItem> lstDonVi = new List<SelectListItem>();
                lstDonVi.Add(new SelectListItem
                {
                    Text = "Chọn đơn vị",
                    Value = "0"
                });
                for (int i = 0; i < temp.Count; i++)
                {
                    lstDonVi.Add(new SelectListItem
                    {
                        Text = temp[i].TenDonVi,
                        Value = temp[i].DonViId.ToString()
                    });
                }

                return Json(lstDonVi, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                //logger.Error(ex.ToString());
                throw;
                //return null;
            }

        }

        public JsonResult CheckUserNameExist(string TAI_KHOAN, int NGUOI_DUNG_ID)
        {
            try
            {
                //_sqlBO = GetSqlBO();
                _sqlBO = GetSqlBOFromPM0(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                bool result = _sqlBO.CheckUserNameExist(TAI_KHOAN);
                if (NGUOI_DUNG_ID > 0 && result)
                {
                    return Json(result);
                }
                // result: true: chua ton tai, nguoc lai da ton tai
                return Json(!result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private USER_GROUP_CREATE RegisterUser(USER_GROUP_CREATE user)
        {
            try
            {
                USER_GROUP_CREATE ret = user;
                if (String.IsNullOrWhiteSpace(ret.UserName))
                {
                    ret.ErrorCode = 1;
                    ret.ErrorMessage = "Xảy ra lỗi. Tên đăng nhập không được rỗng!";
                    return ret;
                }

                ret.ErrorCode = 200;
                var userBO = new UserBO();
                bool result = userBO.RegisterUser(ret);

                if (ret.ErrorCode == 200 && result)
                {
                    UserInGroupBO userInGroupBO = new UserInGroupBO();
                    bool flag = userInGroupBO.AddUserIntoGroup(ret);
                    if (flag == true)
                    {
                        ret.ErrorMessage = "SUCCESS";
                    }
                    else
                    {
                        ret.ErrorCode = -1;
                        ret.ErrorMessage = "Xảy ra lỗi trong khi thêm người dùng vào nhóm";
                    }
                }
                else
                {
                    ret.ErrorCode = 400;
                    ret.ErrorMessage = "Xảy ra lỗi khi thêm người dùng vào hệ thống";
                }

                return ret;
            }
            catch
            {
                throw;
            }

        }

        private USER_GROUP_CREATE GetData(NguoiDungModel model)
        {
            USER_GROUP_CREATE item = new USER_GROUP_CREATE();
            item.Password = "123456qR@";
            item.FullName = model.HO_VA_TEN;
            item.IsActive = 1;
            item.AppCode = Helper.KH_DHQGHN_CODE;
            item.Type = "A";
            item.UserName = model.TAI_KHOAN;
            //if (maDonVi == "KHTC")
            //{
            //    item.GroupCode = "KH";
            //}
            //else if (maDonVi == "BANTNXH")
            //{
            //    item.GroupCode = "DV";
            //}
            //else if (maDonVi == "BANDT")
            //{
            //    item.GroupCode = "BA";
            //}

            //co nhom "QT" la nhom dung de phan quyen chuc nang cho nguoi dung la admin cua tat ca cac don vi
            item.GroupCode = "QT";

            return item;
        }

        public bool UpdateUser(USER_GROUP_CREATE user)
        {
            try
            {
                var userBO = new UserBO();
                return userBO.UpdateUser_DHQG(user);

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private USER_GROUP_CREATE GetUserData(NguoiDungModel model, string userNameOld)
        {
            USER_GROUP_CREATE data = new USER_GROUP_CREATE();
            data.AppCode = Helper.KH_DHQGHN_CODE;
            data.UserName_Old = userNameOld;
            data.Email = string.Empty;
            data.FullName = model.HO_VA_TEN;
            data.UserName = model.TAI_KHOAN;

            return data;
        }

        private NguoiDungAdminBO GetSqlBO()
        {
            return new NguoiDungAdminBO();

        }

        private NguoiDungAdminBO GetSqlBOFromPM0(string connectionString)
        {
            return new NguoiDungAdminBO(connectionString);

        }
    }
}